package com.hserver.system.service;

import com.hserver.system.entity.PermissionEntity;
import com.hserver.system.mapper.PermissionMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.core.server.util.JsonResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Bean
public class PermissionService {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    /**
     * 获取用户的权限
     *
     * @param token
     * @return
     */
    public JsonResult getUserPermissionByToken(String token) {

        /**
         * 可以自己设计修改为redis
         */
        String username = tokenService.getUsernameByToken(token);
        List<PermissionEntity> permissionEntities = userService.getUserPermission(username);
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("success", true);
        List<PermissionEntity> finalPermissionEntities = permissionEntities;
        jsonResult.put("result", new HashMap() {{
            put("menu", finalPermissionEntities);
            put("allAuth", new ArrayList<>());
            put("auth", new ArrayList<>());
        }});
        return jsonResult;
    }

    public List getIdsByRoleId(Integer valueOf) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        List<Integer> p = permissionMapper.getIdsByRoleId(valueOf);
        sqlSession.close();
        return p;
    }

    public void deleteRolePermission(Integer r) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        permissionMapper.deleteRolePermissionByRoleId(r);
        sqlSession.commit();
        sqlSession.close();
    }

    public void saveRolePermission(Integer r, Integer valueOf) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        permissionMapper.saveRolePermission(r, valueOf);
        sqlSession.commit();
        sqlSession.close();
    }

    public void buildRef(PermissionEntity evalEntity, List<PermissionEntity> evalEntities) {
        for (int i = 0; i < evalEntities.size(); i++) {
            PermissionEntity ee = evalEntities.get(i);
            if (ee.getParentId() != null) {
                if (ee.getParentId() == evalEntity.getId()) {
                    if (evalEntity.getChildren() == null) {
                        evalEntity.setChildren(new ArrayList<>());
                    }
                    evalEntity.getChildren().add(ee);
                    buildRef(ee, evalEntities);
                }
            }
        }
    }

    public void removeChild(List<PermissionEntity> evalEntities) {
        for (int i = 0; i < evalEntities.size(); i++) {
            PermissionEntity ee = evalEntities.get(i);
            if (ee.getParentId() != null) {
                evalEntities.remove(ee);
                i--;
            }
        }
    }

    public List<PermissionEntity> page(PermissionEntity permissionEntity) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        List<PermissionEntity> permissionEntities = permissionMapper.list(permissionEntity);
        sqlSession.close();
        for (int i = 0; i < permissionEntities.size(); i++) {
            Map mate = new HashMap();
            mate.put("title", permissionEntities.get(i).getName());
            mate.put("icon", permissionEntities.get(i).getIcon());
            mate.put("keepAlive", true);
            permissionEntities.get(i).setKey(permissionEntities.get(i).getId());
            if (permissionEntities.get(i).getParentId() == null) {
                buildRef(permissionEntities.get(i), permissionEntities);
            }
        }
        removeChild(permissionEntities);
        return permissionEntities;
    }

    public JsonResult add(PermissionEntity permissionEntity) {
        if (permissionEntity.getMenuType() == null) {
            permissionEntity.setMenuType(0);
        }
        if (permissionEntity.getPath() == null) {
            permissionEntity.setPath(permissionEntity.getUrl());
        }
        if (permissionEntity.getName() != null && permissionEntity.getName().trim().length() == 0) {
            return null;
        }
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        int userId = permissionMapper.insert(permissionEntity);
        sqlSession.commit();
        sqlSession.close();
        //userMapper.delRoles(userEntity.);
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("success", true);
        return jsonResult;
    }

    public Boolean add(PermissionEntity permissionEntity, SqlSession sqlSession) {
        if (permissionEntity.getMenuType() == null) {
            permissionEntity.setMenuType(0);
        }
        if (permissionEntity.getPath() == null) {
            permissionEntity.setPath(permissionEntity.getUrl());
        }
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        permissionMapper.insert(permissionEntity);
        sqlSession.commit();
        return true;
    }

    public JsonResult edit(PermissionEntity permissionEntity) {
        if (permissionEntity.getMenuType() == null) {
            permissionEntity.setMenuType(0);
        }
        permissionEntity.setPath(permissionEntity.getUrl());
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        permissionMapper.update(permissionEntity);
        sqlSession.commit();
        sqlSession.close();
        //
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("success", true);
        return jsonResult;
    }

    public JsonResult deleteById(Integer id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        permissionMapper.deleteById(id);
        sqlSession.commit();
        sqlSession.close();
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("success", true);
        return jsonResult;
    }


    public boolean synchronize(PermissionEntity permissionEntity) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        PermissionEntity byNameOne = permissionMapper.getByNameOne(permissionEntity.getName());
        if (byNameOne != null) {
            permissionEntity.setId(byNameOne.getId());
            permissionMapper.update(permissionEntity);
        } else {
            add(permissionEntity);
        }
        sqlSession.commit();
        sqlSession.close();
        return true;
    }

    public void synchronize(String controllerPackageName) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionMapper permissionMapper = sqlSession.getMapper(PermissionMapper.class);
        PermissionEntity byNameOne = permissionMapper.getByNameOne(controllerPackageName);
        if (byNameOne == null) {
            PermissionEntity permissionEntity = new PermissionEntity();
            permissionEntity.setName(controllerPackageName);
            permissionEntity.setRoute(false);
            permissionEntity.setSortNo(20);
            permissionEntity.setMenuType(2);
            add(permissionEntity);
        }
        sqlSession.commit();
        sqlSession.close();
    }

    public Integer synchronizeId(String controllerPackageName) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PermissionEntity byNameOne = sqlSession.getMapper(PermissionMapper.class).getByNameOne(controllerPackageName);
        sqlSession.commit();
        sqlSession.close();
        return byNameOne.getId();
    }

    public JsonResult deleteBatch(String[] id) {
        if (id != null) {
            for (int i = 0; i < id.length; i++) {
                if (id[i] != null && !"".equals(id[i])) {
                    deleteById(Integer.valueOf(id[i]));
                }
            }
        }
        JsonResult jsonResult = JsonResult.ok();
        jsonResult.put("success", true);
        return jsonResult;
    }
}
